package com.servlet;

import com.dao.LoginDao;
import com.dao.imp.LoginDaoImp;
import com.dao.imp.MerchantLogin;
import com.entity.Merchant;
import net.sf.json.JSONObject;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.Map;
import java.util.Set;

/**
 * @author Mathison
 * @Title: ${NAME}
 * @Package: ${PACKAGE_NAME}
 * @Description: TODO
 * @date 2021/11/22 16:04
 **/

@WebServlet(name = "MerchantLoginServlet", value = "/MerchantLoginServlet")
public class MerchantLoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        System.out.println(request.getParameter("username"));
        int userId = Integer.parseInt(request.getParameter("username"));
        String password = request.getParameter("password");

        HttpSession session = request.getSession();
        ServletContext application = session.getServletContext();
        Set<String> onlineMerchantSet;
        Map merchantStatusMap;

        //传入账号密码返回是否验证通过
//        if (){
//            拿到user写入session,map中status==0登陆成功
//        }else {
//            设置status==1,登陆失败
//        }
        MerchantLogin loginTest = new MerchantLogin();

        if(loginTest.login(String.valueOf(userId),password)){
            //拿到登录的用户对象
            Merchant merchant = loginTest.loginResult(String.valueOf(userId),password);
//            System.out.println(merchant.getMerchant_id());
            //添加session属性，标记当前session
            session.setAttribute("MerchantId",merchant.getMerchant_id());
            //拿到application中存放的在线用户集与用户状态图；
            onlineMerchantSet = (Set)application.getAttribute("onlineMerchantSet");
            onlineMerchantSet.add(String.valueOf(merchant.getMerchant_id()));

            merchantStatusMap = (Map)application.getAttribute("merchantStatusMap");
            merchantStatusMap.put(merchant.getMerchant_id(),0);//状态0表示登陆成功
            merchantStatusMap.put(merchant.getMerchant_id()+"nickname",merchant);
//            System.out.println("userID"+merchantStatusMap.get(userId));
//            System.out.println("get:"+merchantStatusMap.get(merchant.getMerchant_id()));
        }else {
            merchantStatusMap = (Map)application.getAttribute("userStatusMap");
            merchantStatusMap.put(userId,1);
        }
//        System.out.println("userstatus:"+merchantStatusMap.get(userId));
        String jsonString = "{status:"+merchantStatusMap.get(userId)+"}";
//        System.out.println(jsonString);
        JSONObject json = JSONObject.fromObject(jsonString);

        response.getWriter().print(json);
    }
}
